package com.zyx.nettypro.netty.protobuf.multi;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/23 11:14
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<PersonPOJO.PersonInfo> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersonPOJO.PersonInfo msg) throws Exception {
        final PersonPOJO.PersonInfo.PersonType personType = msg.getPersonType();

        if (personType == PersonPOJO.PersonInfo.PersonType.StudentType) {
            final PersonPOJO.Student student = msg.getStudent();
            System.out.println("客户端发送数据的类型为StudentType~");
            System.out.println("Student name = " + student.getName() + ", id = " + student.getId());
        } else if (personType == PersonPOJO.PersonInfo.PersonType.WorkerType) {
            final PersonPOJO.Worker worker = msg.getWorker();
            System.out.println("客户端发送数据的类型为WorkerType~");
            System.out.println("Worker name = " + worker.getName() + ", age = " + worker.getAge());
        } else {
            System.out.println("发送的数据类型错误");
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // writeAndFlush 是 write + flush
        // 将数据写入到缓存，并刷新
        // 一般讲，我们对这个发送的数据进行编码
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(>^ω^<)喵", CharsetUtil.UTF_8));
    }

    //处理异常, 一般是需要关闭通道

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
